<template>
    <!-- <van-pull-refresh v-model="isLoading" @refresh="onRefresh"> -->
    <div class="main_topWarp">
        <van-icon class="topWarp_back_btn" @click.stop="goBack()" name="arrow-left" />
        <div>
            <span class="topWarp_title">{{ reportingType.shareName }}</span>
        </div>
    </div>
    <!-- 主体部分 -->
    <div class="DataManaging_box">
        <template v-if="fieldsData.length > 0 && fieldsData !== null">
            <div class="DataManaging_content">
                <div class="DataManaging_main">
                    <!-- 搜索条件 -->
                    <van-cell-group>
                        <van-form>
                            <div class="fieldBox" v-for="(item, index)  in newfieldsData" key="item.id">
                                <van-field v-if="item.fieldDBType === '文本' && item.optionFieldID == null"
                                    :placeholder="`请输入${item.name}`" v-model="formData[index].ConditionValue">
                                    <template #label>
                                        <span @click.stop="handleLabelClick(item)">{{ item.name }}</span>
                                        <van-icon name="arrow" />
                                    </template>
                                    <template #button>
                                        <span
                                            v-if="newfieldsData.length > 0 && newfieldsData[newfieldsData.length - 1].id == item.id"
                                            class="operate-button" @click.stop="addItem(item.id)">
                                            <van-icon name="add-o" />添加
                                        </span>
                                        <span v-if="newfieldsData[0].id !== item.id" class="operate-button"
                                            @click.stop="deleteItem(item)">
                                            <van-icon name="delete" />删除
                                        </span>
                                    </template>
                                </van-field>
                                <van-field v-if="item.fieldDBType === '文本' && item.optionFieldID !== null"
                                    :placeholder="`请选择${item.name}`" v-model="formData[index].ConditionValue" readonly
                                    clickable @click.stop="showOption(item.name)">
                                    <template #label>
                                        <span @click.stop="handleLabelClick(item)">{{ item.name }}</span>
                                        <van-icon name="arrow" />
                                    </template>
                                    <template #button>
                                        <span
                                            v-if="newfieldsData.length > 0 && newfieldsData[newfieldsData.length - 1].id == item.id"
                                            class="operate-button" @click.stop="addItem(item.id)">
                                            <van-icon name="add-o" />添加
                                        </span>
                                        <span v-if="newfieldsData[0].id !== item.id" class="operate-button"
                                            @click.stop="deleteItem(item)">
                                            <van-icon name="delete" />删除
                                        </span>
                                    </template>
                                </van-field>
                                <!-- @input.stop="limitToPositive($event)" -->

                                <van-field v-if="item.fieldDBType == '数字'" type="number" :label="item.name"
                                    :placeholder="`请输入${item.name}`" v-model="formData[index].ConditionValue"
                                    @input.stop="(e) => limitToPositive(e, index)">
                                    <template #label>
                                        <span @click.stop="handleLabelClick(item)">{{ item.name }}</span>
                                        <van-icon name="arrow" />
                                    </template>
                                    <template #button>
                                        <span
                                            v-if="newfieldsData.length > 0 && newfieldsData[newfieldsData.length - 1].id == item.id"
                                            class="operate-button" @click.stop="addItem(item.id)">
                                            <van-icon name="add-o" />添加
                                        </span>
                                        <span v-if="newfieldsData[0].id !== item.id" class="operate-button"
                                            @click.stop="deleteItem(item)">
                                            <van-icon name="delete" />删除
                                        </span>
                                    </template>
                                </van-field>
                                <van-field v-if="item.fieldDBType == '整数'" type="digit" :label="item.name"
                                    :placeholder="`请输入${item.name}`" v-model="formData[index].ConditionValue">
                                    <template #label>
                                        <span @click.stop="handleLabelClick(item)">{{ item.name }}</span>
                                        <van-icon name="arrow" />
                                    </template>
                                    <template #button>
                                        <span
                                            v-if="newfieldsData.length > 0 && newfieldsData[newfieldsData.length - 1].id == item.id"
                                            class="operate-button" @click.stop="addItem(item.id)">
                                            <van-icon name="add-o" />添加
                                        </span>
                                        <span v-if="newfieldsData[0].id !== item.id" class="operate-button"
                                            @click.stop="deleteItem(item)">
                                            <van-icon name="delete" />删除
                                        </span>
                                    </template>
                                </van-field>
                                <van-field v-if="item.fieldDBType == '日期'" name="stepper" :label="item.name"
                                    v-model="formData[index].ConditionValue" readonly clickable placeholder="点击选择日期"
                                    @click.stop="showCalendar = true">
                                    <template #label>
                                        <span @click.stop="handleLabelClick(item)">{{ item.name }}</span>
                                        <van-icon name="arrow" />
                                    </template>
                                    <template #button>
                                        <span
                                            v-if="newfieldsData.length > 0 && newfieldsData[newfieldsData.length - 1].id == item.id"
                                            class="operate-button" @click.stop="addItem(item.id)">
                                            <van-icon name="add-o" />添加
                                        </span>
                                        <span v-if="newfieldsData[0].id !== item.id" class="operate-button"
                                            @click.stop="deleteItem(item)">
                                            <van-icon name="delete" />删除
                                        </span>
                                    </template>
                                </van-field>
                                <van-field v-if="item.fieldDBType == '日期时间'" name="stepper" :label="item.name"
                                    v-model="formData[index].ConditionValue" readonly clickable placeholder="点击选择日期"
                                    @click.stop="showdateCalendar = true">
                                    <template #label>
                                        <span @click.stop="handleLabelClick(item)">{{ item.name }}</span>
                                        <van-icon name="arrow" />
                                    </template>
                                    <template #button>
                                        <span
                                            v-if="newfieldsData.length > 0 && newfieldsData[newfieldsData.length - 1].id == item.id"
                                            class="operate-button" @click.stop="addItem(item.id)">
                                            <van-icon name="add-o" />添加
                                        </span>
                                        <span v-if="newfieldsData[0].id !== item.id" class="operate-button"
                                            @click.stop="deleteItem(item)">
                                            <van-icon name="delete" />删除
                                        </span>
                                    </template>
                                </van-field>

                                <!-- 选择字段弹框 -->
                                <van-popup v-model:show="showPicker" position="bottom" round>
                                    <van-picker title="选择筛选条件" :columns="computedPickerColumns"
                                        @confirm="(value) => onPickerConfirm(value, item.name)" @cancel="cancelPick" />
                                </van-popup>
                                <!-- 日期 -->
                                <template v-if="item.fieldDBType == '日期' && showCalendar">
                                    <van-popup v-model:show="showCalendar" round position="bottom">

                                        <!-- v-model="formData[index].ConditionValue" -->
                                        <van-datetime-picker
                                            @confirm="onConfirm(currentDateYMD, index, item.fieldDBType)"
                                            @cancel="showCalendar = false" v-model="currentDateYMD" type="date"
                                            title="选择完整时间" :formatter="formatter" :min-date="minDate" />

                                    </van-popup>
                                </template>
                                <!-- 日期时间 -->
                                <template v-if="item.fieldDBType == '日期时间' && showdateCalendar">
                                    <van-popup v-model:show="showdateCalendar" round position="bottom">
                                        <van-datetime-picker
                                            @confirm="onConfirm(currentDateALL, index, item.fieldDBType)"
                                            @cancel="showdateCalendar = false" v-model="currentDateALL" type="datetime"
                                            title="选择完整日期时间" :formatter="formatter" :min-date="minDate" />
                                    </van-popup>
                                </template>
                                <!-- 选择字段弹框 -->
                                <van-popup v-model:show="showTopselect" position="bottom" round>
                                    <van-picker title="选择筛选条件" :columns="PickerColumns"
                                        @confirm="(value) => selectPickerConfirm(value, index)"
                                        @cancel="selectCancelPick" />
                                </van-popup>
                            </div>
                        </van-form>

                    </van-cell-group>
                </div>
            </div>

            <!-- 搜索按钮 -->
            <div class="search">
                <van-button block type="primary" class="btn" @click.stop="toReportingPage()">
                    <van-icon name="records" /> 新增
                </van-button>
                <van-button block type="primary" class="btn" @click.stop="onSubmit">
                    <van-icon name="search" /> 搜索
                </van-button>
            </div>

            <!-- 表格 -->
            <div class="table-container">
                <table v-if="dataList && dataList.length > 0">
                    <thead>
                        <div class="thead-wrap" ref="theadWrap">
                            <tr class="tr_theadNew">
                                <th class="td_theadNew fixed-left staticCol">序号</th>
                                <!-- <th class="scrollable-theadContent"  v-for="(header, headerIndex) in headers" :key="headerIndex">{{header}}</th> -->
                                <th class="scrollable-theadContent" v-for="(header, headerIndex) in tableDataHeaders"
                                    :key="headerIndex">{{ header }}</th>
                                <th class="td_theadNew fixed-right  staticCol" v-if="isShow">操作</th>
                            </tr>
                        </div>
                    </thead>
                    <tbody>
                        <div class="tbody-wrap" ref="tbodyWrap">
                            <tr v-for="(item, rowIndex) in dataList" :key="rowIndex" class="tr_new">
                                <td class="td_new tbody-fixed-left staticCon">{{ rowIndex + 1 }}</td>
                                <td class="scrollable-content" v-for="(header, colIndex) in tableDataHeaders"
                                    :key="colIndex">{{
                                        item[header] }}</td>
                                <!-- <td class="scrollable-content"  v-for="prop in Object.keys(item)"  :key="prop">
                                        <span v-if="!fieldsToHide.has(prop)">{{ item[prop] }}</span>    
                                    </td>     -->
                                <td class="td_new tbody-fixed-right  staticCon" v-if="isShow">
                                    <div class=" fbtn">
                                        <div v-has-permission="item.meta_modify_permission == '有'"
                                            @click="handleEdit(item, rowIndex)">
                                            <van-icon name="edit" size="20px" color="#1B57FF" />
                                        </div>
                                        <div v-has-permission="item.meta_delete_permission == '有'"
                                            @click="handleDelete(item)">
                                            <van-icon name="delete" size="20px" color="#1B57FF" />
                                        </div>
                                    </div>
                                </td>
                            </tr>
                        </div>
                    </tbody>
                </table>
                <table v-else>
                    <div slot="no-results" class="noData">
                        <div class="noData_container">
                            <img src="@/assets/img/home/kanban.png" alt="">
                            <div>暂无数据</div>
                        </div>
                    </div>
                </table>
            </div>
            <div class="myPagination">
                <van-pagination class="inner_pagination" v-model="currentPage" :total-items="total" :items-per-page="10"
                    :show-page-size="3" force-ellipses />
            </div>

        </template>
        <!-- 无数据 -->
        <template v-else>
            <div slot="no-results" class="noData">
                <div class="noData_container">
                    <img src="@/assets/img/home/kanban.png" alt="">
                    <div>暂无数据</div>
                </div>
            </div>
        </template>

        <!-- 弹窗 -->
        <van-dialog v-model:show="dialogShow" title="修改" show-cancel-button
            v-model:before-close="onBeforeCloseDialogData">
            <div class="myinformation_dialog_form">
                <van-cell-group>
                    <van-cell v-for="(item, index)  in fieldsData_dialog" :key="index">
                        <van-field v-if="item.fieldDBType == '文本' && item.optionFieldID == null" :label="item.name" type="textarea"
                            :placeholder="`请输入新的${item.name}`" v-model="dialogData[item.name]"></van-field>
                        <van-field v-if="item.fieldDBType == '文本' && item.optionFieldID !== null" :label="item.name" type="textarea"
                            :placeholder="`请选择${item.name}`" v-model="dialogData[item.name]" readonly clickable
                            @click.stop="showOption(item.name)"></van-field>
                        <van-field v-if="item.fieldDBType == '数字'" type="number" :label="item.name"
                            :placeholder="`请输入${item.name}`" v-model="dialogData[item.name]"></van-field>
                        <van-field v-if="item.fieldDBType == '整数'" type="digit" :label="item.name"
                            :placeholder="`请输入${item.name}`" v-model="dialogData[item.name]"></van-field>
                        <van-field v-if="item.fieldDBType == '日期'" :label="item.name" v-model="dialogData[item.name]"
                            readonly clickable placeholder="点击选择日期" @click="showCalendar_dialog = true">
                        </van-field>
                        <van-field v-if="item.fieldDBType == '日期时间'" :label="item.name" v-model="dialogData[item.name]"
                            readonly clickable placeholder="点击选择日期" @click="showdateCalendar_dialog = true">
                        </van-field>
                        <!-- <van-field v-if="item.fieldDBType =='文件位置'" :label="item.name"  v-model="dialogData[item.name]"> -->
                        <van-field v-if="item.fieldDBType == '文件位置'" label-width="80" :label="item.name">
                            <template #input v-if="item.fieldDBType == '文件位置'">
                                <van-uploader result-type="file" max-count="1" :deletable="!detail"
                                    v-model="uploader_dialog" :before-read="beforeRead_dialog"
                                    :after-read="(file) => afterRead_dialog(file, item.name)"
                                    :before-delete="delImg_dialog" />
                            </template>
                        </van-field>

                        <!-- 日期 -->
                        <template v-if="item.fieldDBType == '日期' && showCalendar_dialog">
                            <van-popup v-model:show="showCalendar_dialog" round position="bottom">
                                <van-datetime-picker cancel-button-text=""
                                    @confirm="onConfirm_dialog(currentDateYMD_dialog, item.name, item.fieldDBType)"
                                    @cancel="showCalendar_dialog = false" v-model="currentDateYMD_dialog" type="date"
                                    title="选择完整时间" :formatter="formatter" :min-date="minDate" />

                            </van-popup>
                        </template>
                        <!-- 日期时间 -->
                        <template v-if="item.fieldDBType == '日期时间' && showdateCalendar_dialog">
                            <van-popup v-model:show="showdateCalendar_dialog" round position="bottom">
                                <van-datetime-picker cancel-button-text=""
                                    @confirm="onConfirm_dialog(currentDateALL_dialog, item.name, item.fieldDBType)"
                                    @cancel="showdateCalendar_dialog = false" v-model="currentDateALL_dialog"
                                    type="datetime" title="选择完整日期时间" :formatter="formatter" :min-date="minDate" />
                            </van-popup>
                        </template>
                        <!-- 类型-->
                        <template v-if="item.fieldDBType == '文本' && item.optionFieldID !== null && showFYID == item.id">
                            <van-popup v-model:show="showFYType" round position="bottom">
                                <van-picker :title="'请选择' + item.name" :columns="PickerColumns"
                                    @confirm="(value) => selectPickerConfirm(value, item.name)"
                                    @cancel="selectCancelPick" />
                            </van-popup>
                        </template>
                    </van-cell>
                </van-cell-group>
            </div>
        </van-dialog>
    </div>


    <!-- </van-pull-refresh> -->
</template>

<script>
import { onMounted, reactive, ref, toRefs, computed, watch } from 'vue'
import { Toast, Dialog, Notify } from 'vant';
import { useStore } from "vuex"; // ⚪️ 引入状态管理
import router from "@/router";
import { useRoute } from 'vue-router';
import { ShareDataGetShareFields, ShareDataGetShareData2, ShareFileUpload, ShareDataSaveModifyData, ShareDataDeleteRows, ShareDataGetOptionData, ShareDataGetTableFieldsForModify } from "@/network/DataManagement.js";
export default {
    setup() {
        // 获取当前路由信息
        const route = useRoute();
        const state = reactive({
            isLoading: false,
            reportingType: route.query,
            fieldsData: [], // 后端返回的数据
            newfieldsData: [], // 前端生成的数据
            matchfieldsData: [], // 前端生成的匹配数据
            // 日期展示
            showCalendar: false,
            // 日期时间展示
            showdateCalendar: false,
            // 表头数据集合
            headers: [],
            // 表格数据集合
            dataList: [],
            // 查询参数:
            params: {},
            formData: [],
            // 分页器
            currentPage: 1,
            total: '',
            perPage: '',//每页展示数量

            dialogShow: false, //弹窗
            dialogData: [],


            dialogShow: false, //弹窗
            dialogData: [],
            // 修改弹框
            fieldsData_dialog: [], // 后端返回的数据
            showCalendar_dialog: false,
            showdateCalendar_dialog: false,
            currentDateYMD_dialog: new Date(),
            currentDateALL_dialog: new Date(),
            //图片上传
            flag_dialog: false, // 上传时候禁用上传按钮
            PayImg_dialog: '',
            uploader_dialog: [], // 组件默认显示图片信息
            // 主键数据：
            primaryField: undefined,
            // 是否显示操作
            isShow: false,
            // 需要隐藏的字段名集合
            fieldsToHide: {},
            tableDataHeaders: [],

            // 下拉列表费用类型展示
            showFYID: undefined,
            showFYType: false,
            PickerColumns: [], //下拉列表数据

            // 顶部筛选下拉列表
            showTopselect: false,
        })
        // 表单生成相关
        // let formData = reactive([]);
        let showPicker = ref(false);
        let selectedName = ref('');
        let pickerOptions = reactive([]);
        const currentDateYMD = ref(new Date());
        const currentDateALL = ref(new Date());

        /*****************state**end*************************/

        // 初始化挂载
        onMounted(() => {
            getInitDataList()
            console.log('传过来的数据', state.reportingType);

        });
        // 返回上一页
        const goBack = () => {
            // router.go(-1)
            router.push({
                path: '/DataManagement',
            })
        }
        // 获取我的数据条件筛选项
        const getInitDataList = () => {
            let params = {
                ID: state.reportingType.Id
            }
            ShareDataGetShareFields(params).then((res) => {
                // const fieldsData_dialog = res.data.filter(item => item.isPrimary == "False");
                // state.fieldsData_dialog = fieldsData_dialog;
                const filteredData = res.data.filter(item => item.isPrimary == "False" && item.fieldDBType !== '文件位置');
                state.fieldsData = filteredData;
                state.newfieldsData = [filteredData[0]];
                // 筛选出isPrimary为true的字段
                state.primaryField = res.data.filter(item => item.isPrimary === 'True');
                // 构建需要隐藏的字段名集合
                state.fieldsToHide = new Set(state.primaryField.map(item => item.name));

                // 基于过滤后的数据动态添加属性到formData
                state.newfieldsData.forEach((item, index) => {
                    const formDataItem = {
                        Name: item.name,
                        ConditionValue: '',
                        CompareType: '='
                    };
                    state.formData.push(formDataItem); // 将新对象推入formData数组
                });
                onSubmit()
            })

        }
        // 下拉刷新
        const onRefresh = () => {
            getInitDataList()
            state.isLoading = false
        }

        // 限制输入为正数的处理函数
        const limitToPositive = (event, index) => {
            if (event.target.value) {
                const inputValue = parseFloat(event.target.value);
                if (isNaN(inputValue) || inputValue < 0) {
                    // 如果输入不是数字或小于0，则重置为0
                    event.target.value = '';
                    state.formData[index].ConditionValue = 0; // 根据需要调整这里的逻辑，也可以选择不赋值或赋值为null等
                } else {
                    state.formData[index].ConditionValue = inputValue;
                }
            }

        };
        /***日期选择器****/
        const formatTimeAll = (time) => {
            const datetime = new Date(time);
            const year = datetime.getFullYear();
            const month = String(datetime.getMonth() + 1).padStart(2, '0');
            const day = String(datetime.getDate()).padStart(2, '0');
            const hours = String(datetime.getHours()).padStart(2, '0');
            const minutes = String(datetime.getMinutes()).padStart(2, '0');
            return `${year}-${month}-${day} ${hours}:${minutes}`;
        }
        const formatTimeday = (time) => {
            if (time !== null || time != undefined) {
                const datetime = new Date(time);
                const year = datetime.getFullYear();
                const month = String(datetime.getMonth() + 1).padStart(2, '0');
                const day = String(datetime.getDate()).padStart(2, '0');
                return `${year}-${month}-${day}`;
            } else {
                return null
            }

        }
        // 格式
        const formatter = (type, val) => {
            if (type === 'year') {
                return val + '年';
            }
            if (type === 'month') {
                return val + '月';
            }
            if (type === 'day') {
                return val + '日';
            }
            return val;
        };

        // 日期选择确认
        const onConfirm = (date, index, type) => {
            switch (type) {
                case '日期':
                    state.formData[index].ConditionValue = formatTimeday(date);
                    state.showCalendar = false;
                    break;
                case '日期时间':
                    state.formData[index].ConditionValue = formatTimeAll(date);
                    state.showdateCalendar = false;
                    break;

                default:
                    break;
            }

        };
        // 新增筛选条件
        const addItem = (clickedId) => {
            // 寻找fieldsData中未包含在newfieldsData中的元素
            const availableItems = state.fieldsData.filter(
                (item) => !state.newfieldsData.some((existingItem) => existingItem.id === item.id)
            );
            // 如果有可添加的元素，则随机选择一个添加到newfieldsData（或根据业务逻辑选择）
            if (availableItems.length > 0) {
                // const newItem = {...availableItems[Math.floor(Math.random() * availableItems.length)]};
                const newItem = { ...availableItems[0] };
                state.newfieldsData.push(newItem);

                // 同步更新formData
                const formDataItem = {
                    Name: newItem.name,
                    ConditionValue: '',
                    CompareType: '='
                };
                state.formData.push(formDataItem);
            } else {
                Notify({
                    type: 'danger',
                    message: '没有更多的筛选条件了'
                });
            }
        };



        // label绑定的点击事件
        const handleLabelClick = (item) => {
            state.matchfieldsData = []
            state.matchfieldsData = item
            // 获取所有可用的name，排除已在newfieldsData中的name
            let availableNames = state.fieldsData
                .filter(field => !state.newfieldsData.some(dataItem => dataItem.name === field.name))
                .map(name => name.name);
            // 选择库--正确更新响应式数组
            pickerOptions.length = 0; // 清空现有数组
            availableNames.forEach(item => pickerOptions.push(item)); // 添加新项
            // 显示popup
            showPicker.value = true;

        };
        // 取消
        const cancelPick = () => {
            showPicker.value = false
        }


        // 计算属性来处理当pickerOptions为空时的显示
        const computedPickerColumns = computed(() => {
            // 如果pickerOptions有值，则直接返回它
            if (pickerOptions.length > 0) {
                return pickerOptions.map(column => column);
            }
            // 如果pickerOptions为空，则返回一个包含"暂无更多筛选条件"的数组
            return [{ text: '暂无更多筛选条件', disabled: true }];

        });

        // label确认选择
        const onPickerConfirm = (value, name) => {
            if (value.disabled) {
                showPicker.value = false;
                return;
            } else {
                selectedName.value = value;
                let itemToAdd = state.fieldsData.find(item => item.name === value);

                // 查找要替换的元素的索引
                let indexInNewFields = state.newfieldsData.findIndex(item => item.name === state.matchfieldsData.name);
                let indexInFormData = state.formData.findIndex(formItem => formItem.Name === state.matchfieldsData.name);

                // 如果找到了对应项，则替换；否则，直接添加到末尾
                if (indexInNewFields !== -1) {
                    state.newfieldsData.splice(indexInNewFields, 1, itemToAdd); // 替换newfieldsData中的元素
                }
                // else {
                //     state.newfieldsData.push(itemToAdd); // 如果没有找到匹配项，则直接添加
                // }

                if (indexInFormData !== -1) {
                    state.formData.splice(indexInFormData, 1, {
                        Name: itemToAdd.name,
                        ConditionValue: '',
                        CompareType: '='
                    }); // 替换formData中的元素
                }
                // else {
                //     state.formData.push({ // 如果没有找到匹配项，则直接添加
                //         Name: itemToAdd.name,
                //         ConditionValue: '',
                //         CompareType:'='
                //     });
                // }
                showPicker.value = false;
            }

        };

        // 删除筛选条件
        const deleteItem = (data) => {
            // 从newfieldsData中找到并删除匹配的项
            state.newfieldsData = state.newfieldsData.filter(item => item.id !== data.id);
            state.formData = state.formData.filter(formItem => formItem.Name !== data.name);
            state.params = {}

        };
        /***提交搜索****/
        const onSubmit = () => {
            // const namesArray = state.formData.map(item => `[${item.Name}]`);
            // const newData = namesArray.join(',');
            // 处理条件空值
            const filteredFormData = state.formData.filter(item => item.ConditionValue);
            const condition = filteredFormData.length === 0 ? [] : filteredFormData;

            state.params = {
                mainid: state.reportingType.Id,
                // condition:state.formData,
                // fields:newData,
                condition: condition,
                fields: null,
                order: null,//表示排序字段和排序方式。比如： "ID desc"
                page: 1, // 使用当前页码
                pagecount: 10, // 表示每页记录条数 使用每页展示数量
            }
            state.currentPage = 1
            ShareDataGetShareData2(state.params).then((res) => {
                state.dataList = res.data?.data || []
                state.isShow = state.dataList.some(item =>
                    item.meta_modify_permission === '有' || item.meta_delete_permission === '有'
                );
                state.headers = []
                state.headers = Object.assign({}, state.headers, Object.keys(state.dataList[0] || []));
                //  获取主键字段名
                let primaryFieldNames = state.primaryField.map(field => field.name);
                //  使用Set去重，然后添加额外的字段
                let primaryFieldNames2 = Array.from(new Set([...primaryFieldNames, 'meta_modify_permission', 'meta_delete_permission']));
                // 获取headers对象的所有键
                const keys = Object.keys(state.headers);
                // 过滤出不在列标题无法与主键字段匹配的数组中的键
                const filteredKeys = keys.filter(key => !primaryFieldNames2.includes(state.headers[key]));
                // 从headers对象中取出过滤后的键对应的值
                state.tableDataHeaders = filteredKeys.map(key => state.headers[key]);
                // console.log('tableDataHeaders',state.tableDataHeaders);
                // 分页器
                // 更新总条目数
                state.total = res.data?.total || 0;
            })
        }



        /***表格展示与操作****/
        // 编辑
        const handleEdit = (item, index) => {
            let editParams = {
                mainid: state.reportingType.Id,
                seq: `${item._seq_}`
            }
            ShareDataGetTableFieldsForModify(editParams).then((res) => {
                const fieldsData_dialog = res.data.filter(item => item.isPrimary == "False");
                state.fieldsData_dialog = fieldsData_dialog;
                // 修改表格项dialog的数据
                // let dialogData=fieldsData_dialog
                let dialogData = res.data
                state.dialogData = dialogData.reduce((acc, item) => {
                    // 使用item.name作为key，item.fieldValue作为value
                    acc[item.name] = item.fieldValue;
                    return acc;
                }, {});
            })
            state.dialogShow = true
            // state.dialogData = item
            // 图片显示
            if (item['凭据图片'] != null) {
                state.uploader_dialog = [
                    { url: 'http://ybj.tjxdezx.cn/api/sharefile/showimage?filename=' + item['凭据图片'] },
                ]
            } else {
                state.uploader_dialog = []
            }
        }
        // 删除
        const handleDelete = (item) => {
            Dialog.confirm({
                title: '',
                message: '是否确定删除该条数据？',
            }).then(() => {
                let dParams = {
                    mainid: state.reportingType.Id,
                    pvalues: `${item._seq_}`
                }
                ShareDataDeleteRows(dParams).then((res) => {
                    onSubmit();
                }).catch((error) => {
                    // 处理错误情况
                    // console.error('保存数据时出错:', error);
                });
            }).catch(() => { });

        }
        // 监听currentPage的变化更新数据
        const onPageChange = () => {
            // 当currentPage变化时，调用更新数据的方法
            updateTableData();
        };
        const updateTableData = () => {
            state.params.page = state.currentPage
            ShareDataGetShareData2(state.params).then((res) => {
                state.dataList = res.data?.data || [];
                state.isShow = state.dataList.some(item =>
                    item.meta_modify_permission === '有' || item.meta_delete_permission === '有'
                );
            });
        };
        // 使用watch来监听currentPage的变化
        watch(() => state.currentPage, onPageChange);
        // watch(() => state.currentPage, onPageChange, { immediate: true });

        /*********修改表格项*********/
        const onBeforeCloseDialogData = (action, done) => {

            if (action === "confirm") {
                Dialog.confirm({
                    title: '',
                    message: '是否确定修改该条数据？',
                }).then(() => {
                    // 将收集的表格数据转成特定格式
                    let transformedData = Object.entries(state.dialogData).map(([key, value]) => ({
                        Name: key,
                        FieldValue: value
                    }));
                    // 传入参数
                    let params = {
                        mainid: state.reportingType.Id,
                        data: transformedData
                    }

                    ShareDataSaveModifyData(params).then((res) => {
                        state.dialogShow = false
                        onSubmit();
                    }).catch((error) => {
                        // 处理错误情况
                        console.error('保存数据时出错:', error);
                        state.dialogShow = false;
                    });
                })
                    .catch(() => { });

            } else {
                state.dialogShow = false
                onSubmit();
            }
        }
        // 弹框修改_日期选择确认
        const onConfirm_dialog = (date, index, type) => {
            switch (type) {
                case '日期':
                    state.dialogData[index] = formatTimeday(date);
                    state.showCalendar_dialog = false;
                    break;
                case '日期时间':
                    state.dialogData[index] = formatTimeAll(date);
                    state.showdateCalendar_dialog = false;
                    break;

                default:
                    break;
            }

        };
        /***文件上传****/
        const delImg_dialog = (file, detail) => {
            state.PayImg_dialog = ''; // 只有一张直接清空数组
            return true
        }
        // 上传图片前返回布尔值
        const beforeRead_dialog = (file) => {
            if (
                file.type !== "image/png" &&
                file.type !== "image/jpeg" &&
                file.type !== "image/jpg"
            ) {

                this.$toast.fail("请上传 png,jpg格式图片");
                return false;
            }
            return true;
        }
        const afterRead_dialog = (file, index) => {
            state.flag_dialog = true;
            file.status = "uploading";
            file.message = "上传中...";
            let fileData = new FormData(); // 上传图片要formData类型
            fileData.append("uploadImage", file.file);
            ShareFileUpload(fileData).then((response) => {
                // console.log('response',response);
                // console.log('file',file);
                if (response.success) {
                    file.status = "done";
                    file.message = "上传完成";
                    state.flag_dialog = false;
                    state.PayImg_dialog = response.Data; // 因为只有一张，直接传1个字符串
                    state.dialogData[index] = response.message
                    state.uploader_dialog = [
                        { url: 'http://ybj.tjxdezx.cn/api/sharefile/showimage?filename=' + response.message },
                    ]
                } else {
                    file.status = "failed";
                    file.message = "上传失败";
                }
            });
        }
        // 去往新增页面
        const toReportingPage = () => {
            router.push({
                name: 'DataReporting_M', // 假定dateReporting是你的路由名称
                query: { // 传递参数到dateReporting页面
                    Id: state.reportingType.Id,
                    shareName: state.reportingType.shareName
                }
            });
        }

        // 打开下拉列表
        const showOption = (field) => {
            let fieldId = ''
            let mainid = state.reportingType.Id
            state.fieldsData.forEach(item => {
                if (item.name == field) {
                    fieldId = item.id
                }
            });

            if (state.dialogShow) {
                state.showFYType = true
            } else {
                state.showTopselect = true
            }

            state.showFYID = fieldId
            console.log(state.showFYID);
            GetOptionData(fieldId, mainid)
        }
        // 取消打开下拉列表
        const selectCancelPick = () => {
            if (state.dialogShow) {
                state.showFYType = false
            } else {
                state.showTopselect = false
            }
        }
        // 弹框确认选择
        const selectPickerConfirm = (value, item) => {
            console.log(value);
            console.log(item);
            if (state.dialogShow) {
                state.dialogData[item] = value.value;
                state.showFYType = false
                updateTableData();
            } else {
                state.formData[item].ConditionValue = value.value;
                state.showTopselect = false
            }
        };
        // 获取下拉列表的值
        const GetOptionData = (fieldId, mainid) => {
            let params = {
                ID: fieldId || "",		//字段的ID
                ShareMainID: mainid || "", //分享ID”，
                PageIndex: 1,//页码， 从1开始
                PageSize: 10,//每页大小
                DependencyValue: '' //依赖源字段的值
            }
            ShareDataGetOptionData(params).then((res) => {
                state.PickerColumns = res.data.map(item => {
                    let key = Object.keys(item)[0];
                    return {
                        text: item[key],
                        value: item[key],
                    };
                });

            })
        }


        return {
            ...toRefs(state),
            ...toRefs(pickerOptions),
            // formData,
            showPicker,
            // pickerOptions,
            computedPickerColumns,
            onRefresh,
            goBack,
            onSubmit,
            handleLabelClick, onPickerConfirm, cancelPick,
            addItem, deleteItem,
            limitToPositive,
            // 日期
            currentDateYMD,
            currentDateALL,
            onConfirm,
            minDate: new Date(2024, 0, 1),
            formatter,
            // 表格操作
            handleEdit,
            handleDelete,
            // 分页
            onPageChange,
            updateTableData,
            // 去往新增页面
            toReportingPage,
            // 修改操作相关
            onBeforeCloseDialogData,
            onConfirm_dialog,
            delImg_dialog,
            beforeRead_dialog,
            afterRead_dialog,
            selectCancelPick, selectPickerConfirm, GetOptionData, showOption






        };
    },
};
</script>

<style scoped></style>